# -*- coding:utf-8 -*-

from django.db import models
from weblib.django.user import *
from weblib.django.misc.misc import local_now
#from basemodel.permission import FuncPermissionBase
#from basemodel.permission_utils import *
import json
import re
import itertools
from mako.template import Template

#from setting.models import *


class WrasStyle(models.Model):
    class Meta:
        ordering = ['order']

    selector = models.CharField(max_length=255, default='*', blank=True)

    raw_css = models.TextField(default='', blank=True)
    data_json = models.TextField(default='{}', blank=True)

    enabled = models.BooleanField(default=True, blank=True)
    order = models.FloatField(default=9999, blank=True)

    def __unicode__(self):
        return self.selector

    @property
    def data_dict(self):
        return json.loads(self.data_json, strict=False)

    @property
    def indented_raw_css(self):
        raw_css_lines = self.raw_css.splitlines()
        new_lines = []
        for line in raw_css_lines:
            line = line.strip()
            new_lines.append('    '+line)
        return '\n'.join(new_lines)

    @property
    def css(self):
        raw_css = self.indented_raw_css

        res_list = []
        if '$' not in self.selector:
            # 简单的单条css记录
            res_list.append(u'%s {' % self.selector)
            if raw_css:
                res_list.append(raw_css)

            res_list.append(u'}')
        else:
            # 多条记录
            selector_template = Template(self.selector)

            data_dict = self.data_dict

            var_keys = re.findall('\$\{(\w+?)\}', self.selector)
            used_keys = set()
            var_lists = []
            for k in var_keys:
                if k in used_keys:
                    continue
                var_data = data_dict.get(k, [])
                if isinstance(var_data, (str, unicode)) and var_data.startswith('$'):
                    setting_key = var_data.lstrip('$')
                   # var_data = Setting.get_setting(setting_key, [])
                var_lists.append(var_data)
                used_keys.add(k)

            for var_vals in itertools.product(*var_lists):
                var_combo = dict(zip(var_keys, var_vals))
                VAR_keys = []
                VAR_vals = []
                for var_key in var_keys:
                    var_val = var_combo[var_key]
                    VAR_key = var_key.upper()
                    VAR_data = data_dict.get(VAR_key, {})
                    if isinstance(VAR_data, (str, unicode)) and VAR_data.startswith('$'):
                        setting_key = VAR_data.lstrip('$')
                       # VAR_data = Setting.get_setting(setting_key, {})

                    if isinstance(VAR_data, list):
                        var_list = data_dict.get(var_key, [])
                        try:
                            i = var_list.index(var_val)
                            VAR_val = VAR_data[i]
                        except (ValueError, IndexError):
                            VAR_val = ''
                    else:
                        VAR_val = VAR_data.get(var_val, '')

                    VAR_keys.append(VAR_key)
                    VAR_vals.append(VAR_val)
                total_combo = dict(zip(VAR_keys, VAR_vals))
                total_combo.update(var_combo)

                one_selector = selector_template.render(**var_combo)

                tmp_style_template = Template(raw_css)
                one_style = tmp_style_template.render(**total_combo)

                res_list.append(u'%s {' % one_selector)
                res_list.append(one_style)
                res_list.append(u'}')

        return u'\n'.join(res_list)


class WrasModule(models.Model):
    class Meta:
        ordering = ['order']

    name = models.CharField(max_length=32, default='UnnamedModule', unique=True, blank=True)
    zh_name = models.CharField(max_length=32, default=u'未命名模块', blank=True)
    desc = models.TextField(default='', blank=True)

    order = models.FloatField(default=100, blank=True)
    enabled = models.BooleanField(default=False, blank=True)
    public = models.BooleanField(default=False, blank=True)

    has_sub_url = models.BooleanField(default=False, blank=True)

    # front_type = models.CharField(max_length=16, null=True, blank=True,
    #                               choices=(
    #                                   ('plugin', 'plugin'),
    #                                   ('toolpane', 'toolpane'),
    #                                   ('page', 'page'),
    # ))

    # py = models.CharField(max_length=255, null=True, blank=True)
    # html = models.CharField(max_length=255, null=True, blank=True)
    js = models.CharField(max_length=1024, null=True, blank=True)
    css = models.CharField(max_length=1024, null=True, blank=True)
    icon_class = models.CharField(max_length=64, default='fa fa-cube', blank=True)

    info_json = models.TextField(default='{}', blank=True)

    def __unicode__(self):
        return self.name

    @property
    def info(self):
        return json.loads(self.info_json, strict=False)
    @info.setter
    def info(self, new_info):
        if isinstance(new_info, (str, unicode)):
            self.info_json = new_info
        else:
            self.info_json = json.dumps(new_info, indent=4)

    @property
    def js_list(self):
        if self.js:
            return [tk.strip() for tk in self.js.split(',')]
        else:
            return []

    @property
    def css_list(self):
        if self.css:
            return [tk.strip() for tk in self.css.split(',')]
        else:
            return []


# class User_Module(FuncPermissionBase):
#     """ Permission middle table between user and module
#     """
#     class Meta:
#         pass
#
#     user = models.ForeignKey(AUTH_USER_MODEL)
#     module = models.ForeignKey(WrasModule, related_name='user_permissions')
#
#     def __unicode__(self):
#         return u"%s - %s" % (self.user, self.module)
#
#
# class Company_Module(FuncPermissionBase):
#     """ Permission middle table between company and module
#     """
#     class Meta:
#         pass
#
#     company = models.ForeignKey('dxuser.Company')
#     module = models.ForeignKey(WrasModule, related_name='company_permissions')
#
#     def __unicode__(self):
#         return u"%s - %s" % (self.company, self.module)
#
#
# module_perm_checker = FuncPermissionChecker()